<template>
  <div class="app-container">
    <div style="margin-bottom: 20px">
      <el-button
        type="primary"
        size="small"
        icon="el-icon-back"
        style="margin-left: 20px"
        :loading="loading"
        @click="toList"
      >返回文章列表</el-button>
      <el-button
        v-show="typeProp !== 'view'"
        type="primary"
        size="small"
        icon="el-icon-check"
        style="margin-left: 20px"
        :loading="loading"
        @click="handleSubmit"
      >提 交</el-button>
      <el-button
        v-show="typeProp !== 'view'"
        type="primary"
        size="small"
        icon="el-icon-delete"
        style="margin-left: 20px"
        :loading="loading"
        @click="handleEmpty"
      >清 空</el-button>
    </div>
    <avue-form
      ref="formArticle"
      v-model="formArticle"
      :option="optionForm"
      :upload-before="uploadBefore"
      :upload-after="uploadAfter"
      :upload-error="uploadError"
      @reset-change="handleEmpty"
      @submit="handleSubmit"
    >
      <template slot="content">
        <div>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
              <div id="editor" ref="editor" class="text" />
            </el-col>
            <el-col :xs="24" :sm="24" :md="9" :lg="9" :xl="8">
              <div>内容预览：</div>
              <div v-html="editorContent" />
            </el-col>
          </el-row>
        </div>
      </template>
    </avue-form>
  </div>
</template>

<script>
import { update, add } from '@/api/operation/article';
import { qiniuUpload } from '@/api/tools/qiniu';
import { mapGetters } from 'vuex'
import CONFIG from '@/config/index';
import DIC from '@/config/dicData';
import E from 'wangeditor';

export default {
  name: 'ArticleForm',
  props: {
    formProp: {
      type: Object,
      default: () => {
        return {};
      }
    },
    typeProp: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  data() {
    return {
      editor: null,
      editorContent: '',
      imgURL: '',
      formArticle: {},
      data: [],
      loading: false,
      optionForm: {
        title: '文章表单',
        align: 'center',
        menuAlign: 'center',
        column: [
          {
            label: '标题',
            prop: 'title',
            span: 6,
            readonly: false,
            rules: [
              {
                required: true,
                message: '请输入标题',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '作者',
            prop: 'author',
            span: 6,
            readonly: false,
            rules: [
              {
                required: true,
                message: '请输入作者名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '发布状态',
            prop: 'publish',
            type: 'switch',
            value: 0,
            span: 6,
            disabled: false,
            dicData: DIC.article_publish
          },
          {
            label: '审核状态',
            prop: 'status',
            type: 'switch',
            value: 0,
            span: 6,
            disabled: false,
            dicData: DIC.article_status
          },
          {
            label: '排序',
            prop: 'sort',
            span: 6,
            value: 1,
            disabled: false,
            type: 'number'
          },
          {
            label: '封面',
            prop: 'coverName',
            type: 'upload',
            disabled: false,
            limit: 1,
            accept: ['image/jpeg', 'image/png'],
            listType: 'picture-img',
            dataType: 'string',
            action: CONFIG.uploadApi,
            propsHttp: {
              home: CONFIG.uploadUrl,
              url: 'fileName',
              fileName: 'imgFile'
            },
            tip: `只能上传jpg/png图片，且不超过${CONFIG.bannerLimitSize}M`,
            rules: [
              {
                required: true,
                message: '请上传图片',
                trigger: 'change'
              }
            ]
          },
          {
            label: '文章内容',
            prop: 'content',
            span: 24,
            formslot: true,
            disabled: false,
            rules: [
              {
                required: true,
                message: '请输入文章内容',
                trigger: 'blur'
              }
            ]
          }
        ]
      }
    };
  },
  watch: {
    formProp(val) {
      if (val) {
        this.formArticle = this.formProp;
        this.imgURL = this.formProp.coverUrl;
        this.editorContent = this.formProp.content;
        this.editor.txt.html(this.editorContent);
      }
    },
    typeProp(val) {
      // 点击表格查看按钮表单标题和作者为只读状态 其他为禁用状态
      const isView = val === 'view';
      this.optionForm.column.forEach(item => {
        if (['title', 'author'].includes(item.prop)) {
          item.readonly = isView;
        } else {
          item.disabled = isView;
        }
      });
      if (val === 'view') {
        this.editor.disable(); // 富文本禁用
      } else {
        this.editor.enable(); // 富文本解禁
      }
    }
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    // 初始化富文本插件
    initEditor() {
      var editor = new E(this.$refs.editor); // 实例化富文本插件
      // 自定义菜单配置
      editor.config.zIndex = 5;
      // 设置编辑区域高度为 500px
      editor.config.height = 500;
      // 文件上传
      editor.config.customUploadImg = function(files, insert) {
        // files 是 input 中选中的文件列表
        // insert 是获取图片 url 后，插入到编辑器的方法
        files.forEach(image => {
          qiniuUpload(image).then(res => {
            const data = res.data;
            const url = CONFIG.uploadUrl + data.fileName;
            insert(url);
          });
        });
      };
      editor.config.onchange = html => {
        this.editorContent = html;
      };
      editor.create();
      // 初始化数据
      editor.txt.html(this.editorContent);
      this.editor = editor;
    },
    toList() {
      this.$emit('hide');
      this.handleEmpty();
    },
    uploadBefore(file, done, loading) {
      const limitSize = file.size / 1024 / 1024 < CONFIG.articleCoverLimitSize;
      if (!limitSize) {
        this.$message.error('图片大小超过限制');
        this.formArticle.imgURL = '';
        loading();
        return;
      }
      done();
    },
    uploadAfter(res, done) {
      this.imgURL = CONFIG.uploadUrl + res.fileName;
      // 因为coverUrl是完整地址 这里要给表单中重新赋值 否则不显示
      // 设置定时器防止form底层默认修改
      setTimeout(() => {
        this.formArticle.coverUrl = this.imgURL;
      }, 1000);
      done();
    },
    uploadError(error, column) {
      console.log('uploadError', error, column);
      this.$message.error('上传图片失败，请重试');
    },
    handleEmpty() {
      this.editorContent = '';
      this.editor.txt.html(this.editorContent);
      this.formArticle = {
        publish: 0,
        status: 0,
        title: '',
        author: '',
        sort: 1,
        coverUrl: '',
        coverName: '',
        content: ''
      };
    },
    handleSubmit() {
      this.formArticle.content = this.editorContent;
      this.formArticle.coverUrl = this.imgURL; // 防止coverUrl为空的处理
      this.formArticle.createUser = this.user.username; // 添加创建人
      this.$refs.formArticle.validate((vaild, done) => {
        if (vaild) {
          this.loading = true;
          if (this.typeProp === 'edit') {
            update(this.formArticle)
              .then(res => {
                this.loading = false;
                this.$message.success('修改成功');
                this.$emit('submitHandle');
                this.handleEmpty();
                done();
              })
              .catch(err => {
                this.loading = false;
                this.$message.error('修改失败' + err);
              });
          } else {
            add(this.formArticle)
              .then(() => {
                this.loading = false;
                this.$message.success('新增成功');
                this.$emit('submitHandle');
                this.handleEmpty();
                done();
              })
              .catch(err => {
                this.loading = false;
                this.$message.error('新增失败' + err);
              });
          }
        }
      });
    }
  }
};
</script>
